//index.js
const app = getApp()

const amapFile = require('../../libs/amap-wx')
const myAmapFun = new amapFile.AMapWX({key:'b4ce118f7566786b64c8c7835ed7af8f'});

Page({
  data: {
    userInfo: {},
    logged: true,
    markers:[], // 地图上标记的点
    isSignLocation:false,   // 是否处于标记位置的状态中
    markLat:0,
    markLong:0,
    currentLat:0,
    currentLong:0,
    polyline:[],    
    showMap:false,
  },
  onLoad: function(query) {
    if(query.lat){
      this.data.markLat = query.lat;
    };
    if(query.lng){
      this.data.markLong = query.lng;
    };
    this.authUserInfo();
  },
  /// 检查用户状态
  authUserInfo(){
    if (app.globalData.userInfo && app.globalData.id) {
      console.log("全局变量缓存的有用户信息");
      this.dealWithUserInfo(app.globalData.userInfo);
      return;
    }
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.userInfo']) {
          this.setData({
            logged:false,
          })
        } else {
          wx.getUserInfo({
            success: (res) => {
              console.log("已授权后直接获取用户信息");
              this.dealWithUserInfo(res.userInfo);
            },
          })
        }
      },
    })
  },
  /// 获取用户信息,通过openType触发
  getUserInfo: function(e) {
    console.log("通过登录按钮获取用户信息");
    this.dealWithUserInfo(e.detail.userInfo);
  },
  onShareAppMessage: function(e){
    if (this.data.markLat == 0 || this.data.markLong == 0) {
      wx.showToast({
        title: '请标记目标位置',
        icon: 'none'
      });
    }else{
      return {
        title: '室外停车场寻车导航',
        path: '/pages/index/index?lat=' + this.data.markLat + '&lng=' + this.data.markLong
      }
    }
    
  },
  /// 获取完用户信息之后
  dealWithUserInfo(userInfo){
    app.globalData.userInfo = userInfo;
    this.setData({
      userInfo: userInfo,
      logged: true
    })
    this.onGetOpenid();
    this.authLocation();
  },
  /// 检查定位权限
  authLocation(){
       wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userLocation']) {
            this.moveToCurrentLocation();
          } else {
            wx.authorize({
              scope: 'scope.userLocation',
              success:res=>{
                this.moveToCurrentLocation();
              },
            })
          }
        }
      })
  },
  /// 移动到当前位置
  moveToCurrentLocation(){
    wx.showToast({
      title: '加载中...',
      icon: 'none'
    });
    wx.getLocation({
      type:'gcj02',
      isHighAccuracy:true,
      success:res=>{
        setTimeout(() => {
          wx.hideLoading();
        }, 5000);
        const latitude = res.latitude
        const longitude = res.longitude
        this.setData({
          currentLong:longitude,
          currentLat:latitude,
          showMap:true,
        })
      },
    })
  },
  /// 获取openid
  onGetOpenid: function() {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {userInfo:this.data.userInfo},
      success: res => {
        console.log('[云函数] [login] user openid: ', JSON.stringify(res));
        app.globalData.openid = res.result.openid
        app.globalData.id = res.result.id;
        if (res.result.geo) {
          this.showMarker(res.result.geo.coordinates[0],res.result.geo.coordinates[1]);
        }
        
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },
  /// 地图区域改变
  regionChange(event){
    console.log("地图区域变化")
    if (this.data.isSignLocation && event.type === 'end') {
      const mapContext = wx.createMapContext("map",this);
      mapContext.getCenterLocation({
        success:res=>{
          this.showMarker(res.longitude,res.latitude)
        },
      })
    }
  },
  /// 标记点
  markerTap(event){
    console.log('标记点击' + JSON.stringify(event))
  },
  /// 点击地图上任意位置，（bug没触发）
  pointTapped(event){
    if (!this.data.isSignLocation) {
      return;
    }
    console.log('点击某个点' + JSON.stringify(event));
    if (this.data.isSignLocation) {
      this.showMarker(event.detail.longitude,event.detail.latitude)
    }
  },
  showMarker(long,lat){
    this.data.markLong = long
    this.data.markLat = lat
    this.setData({
      markers:[{
        iconPath: "./car.gif",
        id: 0,
        latitude: lat,
        longitude: long,
        width: 30,
        height: 30
      }],
    })
  },
  /// 结束标记
  overSign(){
    this.setData({
      isSignLocation:false,
    })
     // 调用云函数
     wx.cloud.callFunction({
      name: 'uploadGeo',
      data: {
        id:app.globalData.id,
        longitude:this.data.markLong,
        latitude:this.data.markLat,
      },
      success: res => {
        console.log('存储成功');
      },
      fail: err => {
        console.log('存储失败');
      }
    })
  },
  /// 点击导航
  navigate(){
    if (this.data.markLat == 0 || this.data.markLong == 0) {
      wx.showToast({
        title: '请标记目标位置',
        icon: 'none'
      })
      return;
    }
    wx.openLocation({
      longitude: this.data.markLong,
      latitude: this.data.markLat
    })
  },
  /// 点击标记位置
  signLocation(){
    let that = this;
    if(this.data.markLat && this.data.markLong){
      wx.showModal({
        title: '提示',
        content: '是否重新标记位置',
        success(res) {
          if (res.confirm) {
            that.data.markLat = 0;
            that.data.markLong = 0;
            that.setData({
              isSignLocation: true,
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      });
    }else{
      this.setData({
        isSignLocation: true,
      })
    }
    
  },
  /// 点击路线规划
  showRoad(){
    if (this.data.markLat == 0 || this.data.markLong == 0) {
      wx.showToast({
        title: '请标记目标位置',
        icon: 'none'
      })
      return;
    }
    myAmapFun.getWalkingRoute({
      origin:this.data.currentLong + ',' + this.data.currentLat,
      destination:this.data.markLong + ',' + this.data.markLat,
      fail:err=>{
        console.log(err);
      },
      success:(data)=>{
        var points = [];
        if (!data.paths || !data.paths[0] || !data.paths[0].steps) {
          wx.showToast({ title: '失败！' });
          return;
        }
        if (data.paths && data.paths[0] && data.paths[0].steps) {
          var steps = data.paths[0].steps;
          for (var i = 0; i < steps.length; i++) {
            var poLen = steps[i].polyline.split(';');
            for (var j = 0; j < poLen.length; j++) {
              points.push({
                longitude: parseFloat(poLen[j].split(',')[0]),
                latitude: parseFloat(poLen[j].split(',')[1])
              })
            }
          }
        }
        this.setData({
          // distance: data.paths[0].distance,
          // cost: parseInt(data.paths[0].duration / 60),
          polyline: [{
            points: points,
            width: 6,
            color:'#ff0000',
          }]
        });
      },
    })
  },
})
